package com.ddm.service.impl;

import com.ddm.exception.DataErrorException;
import com.ddm.service.CommonService;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;

/**
 * @author 丁丁猫
 * @version 1.0
 */
@Service
public class CommonServiceImpl implements CommonService {
    /**
     * 将List<String>转换为String
     * @param imageList
     * @return
     */
    @Override
    public String convertListToString(List<String> imageList) {
        if (imageList == null || imageList.isEmpty()) {
            return null;
        }
        return String.join(",", imageList);
    }

    /**
     * 将String转换为List<String>
     * @param images
     * @return
     */
    @Override
    public List<String> convertStringToList(String images) {
        if (images == null || images.isEmpty()) {
            return null;
        }
        return Arrays.asList(images.split(","));
    }

    /**
     * numId提取数字ID
     * @param numId
     * @param level
     * @return
     */
    @Override
    public String extractNumId(String numId, Integer level) {
        // 空值检查
        if (numId == null || numId.isEmpty()) {
            throw new DataErrorException("numId是空值");
        }
        // numId 是类似 "12,5,3" 的字符串，按逗号分割，取最后一个值并转换为 Long
        String[] parts = numId.split("\\.");
        int size = parts.length;
        //返回最后一个值
        if (level == -1) {
            return parts[size-1];
        }
        if (level < 1 || level > size) {
            throw new DataErrorException("level值不在1-4之间");
        }
        //取第level个值
        return parts[level-1];
    }

    /**
     * 去除字符串中的逗号
     * @param numId
     * @return
     */
    @Override
    public String removeCommas(String numId) {
        if (numId == null || numId.isEmpty()) {
            throw new DataErrorException("numId是空值");
        }
        return numId.replace(".", "");
    }
}
